package br.com.vti.leilao.model.business;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import br.com.vti.leilao.model.business.exception.ApplicationException;
import br.com.vti.leilao.model.dao.Dao;
import br.com.vti.leilao.model.entity.Lance;
import br.com.vti.leilao.view.util.MessageFactory;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author ednardomatos
 */
@Component("lanceBusiness")
@Transactional(readOnly = true)
public class LanceBusinessImpl extends BusinessImpl<Lance, ApplicationException> implements LanceBusiness {
    
    private static final long serialVersionUID = -3897867461694722465L;
    
    @Autowired
    @Qualifier("dao")
    private Dao<Lance> dao;
        
    @Autowired
    @Qualifier("messageFactory")
    private MessageFactory messageFactory;

    @Override
    public Dao<Lance> getDao() {
        return dao;
    }

    @Override
    public void setDao(Dao<Lance> dao) {
        this.dao = dao;
    }

    @Override
    public MessageFactory getMessageFactory() {
        return messageFactory;
    }

    @Override
    public void setMessageFactory(MessageFactory messageFactory) {
        this.messageFactory = messageFactory;
    }
    
    @Override
    public Lance consultarUltimoLance(Lance lance) {
        Lance lanceRet = null;
        if (lance != null && lance.getLeilaoFk() != null &&
            lance.getLeilaoFk().getId() != null && lance.getLeilaoFk().getId() > 0) {
            try {
                String hql = "FROM Lance lc1 WHERE lc1.leilaoFk.id = :idLeilao AND lc1.vlrLance = (SELECT MAX(lc2.vlrLance) FROM Lance lc2 WHERE lc2.leilaoFk.id = :idLeilao) ORDER BY id DESC";
                Map<String, Object> parametros = new HashMap<String, Object>();
                parametros.put("idLeilao", lance.getLeilaoFk().getId());
                List<Lance> lista = getDao().listarPorHql(hql, parametros, 1);
                if (lista != null && !lista.isEmpty()) {
                    lanceRet = lista.get(0);
                }
            } catch (SQLException ex) {
                getLogger().error(ex.getMessage());
            }
        }
        return lanceRet;
    }

}
